from flask import Blueprint,Flask, request, jsonify, Response, render_template, send_from_directory
from db.sqlite import SQLiteDB
from queue import Queue
import asyncio
import threading
import time

from utils.login import get_tencent_cookie, douyin_cookie_gen, get_ks_cookie, xiaohongshu_cookie_gen
active_queues = {}

account_router = Blueprint('account', __name__, url_prefix='/account')

@account_router.route("/getValidAccounts",methods=['GET'])
async def getValidAccounts():
        # 从数据库查询
    results = []
    with SQLiteDB() as db:
        query_sql = "SELECT * FROM account WHERE status = ?"
        results = db.query(query_sql, (1,))
    return jsonify({"code":200,"msg": "success","data":results})

@account_router.route('/update', methods=['POST'])
def update():
    data = request.get_json()
    id = data.get('id')
    name = data.get('name')
    try:
        with SQLiteDB() as db:
            query_sql = "UPDATE account SET name = ? WHERE id = ?"
            db.execute(query_sql, (name,id,))
            db.commit()
        return jsonify({"code": 200,  "msg": "account update successfully", "data": None})

    except Exception as e:
        return jsonify({ "code": 500, "msg": str("update failed!"),  "data": None })


@account_router.route('/delete', methods=['GET'])
def delete():
    id = int(request.args.get('id'))
    try:
        # 获取数据库连接
        with SQLiteDB() as db:
            query_sql = "DELETE FROM account WHERE id = ?"
            db.execute(query_sql, (id,))
            db.commit()

        return jsonify({ "code": 200, "msg": "account deleted successfully","data": None})

    except Exception as e:
        return jsonify({ "code": 500, "msg": str("delete failed!"), "data": None})
    

@account_router.route("/statistics",methods=['GET'])
def statistics():

    with SQLiteDB() as db:
        # 账号统计
        account_list = db.query('''SELECT type,COUNT(*) as count FROM account group by type''')
        # 遍历叠加 list 得到 total
        account_total = 0
        for item in account_list:
            account_total += item['count']

        # 任务统计
        job_list = db.query('''SELECT status,COUNT(*) as count FROM job group by status''')
        job_total = 0
        for item in job_list:
            job_total += item['count']

        # 资源统计
        file_count = db.query('''SELECT COUNT(*) as count FROM file''')[0]['count']
        topic_count = db.query('''SELECT COUNT(*) as count FROM topic''')[0]['count']
        category_count = db.query('''SELECT COUNT(*) as count FROM category''')[0]['count']
        source_total = file_count + topic_count + category_count

        info = {
            "account" : {"total": account_total, "list": account_list},
            "job" : {"total": job_total, "list": job_list},
            "source" : {"total": source_total,"file": file_count, "topic": topic_count,"category":category_count},
        }
    return jsonify({"code": 200, "msg": None,"data": info})

@account_router.route('/login')
def login():
    # 1 小红书 2 视频号 3 抖音 4 快手
    type = request.args.get('type')
    # 账号名
    id = request.args.get('id')

    # 模拟一个用于异步通信的队列
    status_queue = Queue()
    active_queues[id] = status_queue

    def on_close():
        print(f"清理队列: {id}")
        del active_queues[id]
    # 启动异步任务线程
    thread = threading.Thread(target=run_async_function, args=(type,id,status_queue), daemon=True)
    thread.start()
    response = Response(sse_stream(status_queue,), mimetype='text/event-stream')
    response.headers['Cache-Control'] = 'no-cache'
    response.headers['X-Accel-Buffering'] = 'no'  # 关键：禁用 Nginx 缓冲
    response.headers['Content-Type'] = 'text/event-stream'
    response.headers['Connection'] = 'keep-alive'
    return response


# 包装函数：在线程中运行异步函数
def run_async_function(type,id,status_queue):
    match type:
        case '1':
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.run_until_complete(xiaohongshu_cookie_gen(id, status_queue))
            loop.close()
        case '2':
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.run_until_complete(get_tencent_cookie(id,status_queue))
            loop.close()
        case '3':
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.run_until_complete(douyin_cookie_gen(id,status_queue))
            loop.close()
        case '4':
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.run_until_complete(get_ks_cookie(id,status_queue))
            loop.close()
# SSE 流生成器函数
def sse_stream(status_queue):
    while True:
        if not status_queue.empty():
            msg = status_queue.get()
            yield f"data: {msg}\n\n"
        else:
            # 避免 CPU 占满
            time.sleep(0.1)